package view;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.MemoryImageSource;
import java.util.List;

import javax.swing.*;

import model.Model;

public class MainWindow extends javax.swing.JPanel {
	private static final long serialVersionUID = 6832867090834513168L;
	private Image src = null;
    public MainWindow() {
        new Worker().execute();
    }
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (src != null) g.drawImage(src, 0, 0, this);
    }
    private class Worker extends SwingWorker<Void, Image>{
        private Model model = Model.getInstance();
        protected void process(List<Image> chunks){
            for (Image bufferedImage : chunks){
                src = bufferedImage;
                repaint();
            }
        }
        protected Void doInBackground() throws Exception{
//            int frames = 0;
            int[] mem = new int[model.xSize * model.ySize];
            long start = 0;
            long time = 0;
            int runs = 0;
//            long last = start;
            while (true){
            	if(runs==0)
            		start = System.currentTimeMillis();
                for (int y = 0; y < model.ySize; y++)
                    for (int x = 0; x < model.xSize; x++)
                        mem[x + y * model.xSize] = model.getColor(x,y);
                Image img = createImage(new MemoryImageSource(model.xSize, model.ySize, mem, 0, model.xSize));
                BufferedImage bi = new BufferedImage(model.xSize, model.ySize, BufferedImage.TYPE_INT_ARGB);
                Graphics2D g2 = bi.createGraphics();
                g2.drawImage(img, 0, 0, null);
                g2.dispose();
                publish(bi);
                runs++;
                if(runs==1000){
	                time = System.currentTimeMillis() - start;
	                System.out.println("FPS: " + ((1000*1000)/time));
	                runs=0;
	                start = System.currentTimeMillis(); 
                }
//                this.wait(1000);
//                last = System.currentTimeMillis();
//                frames++;
            }
//            System.err.println("Frames = " + frames + ", fps = " + ((double) frames / (last - start) * 1000));
//            return null;
        }
    }
}